#include <yolov3_clip_detector.h>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <cstdio>



void ReadImage(std::string imgdirs, std::vector<std::string>&image_paths){
  DIR *dir;
  if ((dir = opendir(imgdirs.c_str())) == nullptr){
    throw std::runtime_error("dircetory " + imgdirs + "does not exit");
  }
  dirent * dp;
  for (dp = readdir(dir); dp !=nullptr; dp=readdir(dir)){
    const std::string file_name = dp->d_name;
    if (file_name == "." || file_name==".."){
      continue;
    }
    image_paths.push_back(file_name);
  }
  closedir(dir);
}


void TEST()
{
  optical_clip_detector::Yolov3CLIPDetector resource_;
  std::string imgdir = "/home/xjl/ccode/imagebind_test_1025/dataset/";
  bool flag = false;
  std::ofstream out_file; 
  std::string output = "/home/yk/zh/data/test_data/fxcs/20240920/episode/1004/missionName/results_2/";
  std::vector<std::string> imgfiles;
  std::cout<<"start1"<<std::endl;
  resource_.Initialize();
  ReadImage(imgdir, imgfiles);
  for (auto name: imgfiles){
    size_t pos = name.find('.');
    std::string filename = name.substr(0, pos);
    std::cout<<"file: "<<filename<<std::endl;
    std::vector<cv::Rect2d> vecRoi;
    std::vector<std::string> vecName;
    std::vector<float> confidenc;
    std::string image_path = imgdir +"/"+ name;
    std::cout<<image_path<<std::endl;
    cv::Mat cv_img = cv::imread(image_path, cv::IMREAD_COLOR);
    cv::Mat new_img = cv_img.clone();
    std::cout<<"shape: "<<new_img.rows<<", "<<new_img.cols<<std::endl;
    std::unordered_set<std::string> target_names{"Warplane"};
    flag = resource_.inference(cv_img, vecRoi, vecName, confidenc);
    if (vecRoi.empty()){
      std::cout<<"Detect nothing"<<std::endl;
    }else{
      for (int i=0; i <vecRoi.size(); i++){
        std::string class_name = vecName[i];
        std::string class_filePath = output + class_name + ".txt";
        out_file.open(class_filePath, std::ios::out | std::ios::app);
        out_file<<filename<<" "<<confidenc[i]<<" "<<vecRoi[i].x<<" "<<vecRoi[i].y<<" "<< vecRoi[i].x + vecRoi[i].width << " "<< vecRoi[i].y + vecRoi[i].height<<std::endl;
        out_file.close();
        std::cout<<"object name: "<<class_name<<", conf: "<<confidenc[i]<<std::endl;
      }
    }
    break;
    std::cout<<"----------------------------------------------"<<std::endl;
    std::cout<<"end a picture"<<std::endl;
  }

}


// Run all the tests that were declared with TEST()
int main(int argc, char ** argv)
{
  TEST();
}
